import urllib

import aiohttp
import lxml.html
import json
import asyncio
import time
import random

import re
from PIL import Image
import io
import logging
import sys
import os
import aioredis
sys.path.append(os.path.abspath('../'))
from tongji import aget_wxqrcode

logger = logging.getLogger("cmcc")


def get_uuid():
    token = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'
    new_token = ""
    for i in token:
        r = int(random.random() * 16) | 0
        if i == 'x':
            new_token += "%x" % r
        elif i == 'y':
            new_token += "%x" % (r & 0x3 | 0x8)
        else:
            new_token += i
    return new_token


def get_ts():
    return str(time.time()).replace('.', '')[:13]

card = {'100': {'cardValCode': '04',
                'cardValue': '10000',
                'offerRate': '1',
                'offerRateId': ''},
        '20': {'cardValCode': '01',
               'cardValue': '2000',
               'offerRate': '1',
               'offerRateId': ''},
        '30': {'cardValCode': '02',
               'cardValue': '3000',
               'offerRate': '1',
               'offerRateId': ''},
        '300': {'cardValCode': '05',
                'cardValue': '30000',
                'offerRate': '1',
                'offerRateId': ''},
        '50': {'cardValCode': '03',
               'cardValue': '5000',
               'offerRate': '1',
               'offerRateId': ''}}

async def get_unicom_wx(user_tel, amount, redis):
    upay_redis = await aioredis.create_redis(address=('localhost', 6379), db=1)
    upay_data_s = await upay_redis.rpop('tickets')
    upay_data = json.loads(upay_data_s.decode())
    upay_id = upay_data["upay"]
    ticket = upay_data['ticket']
    logger.info("下单%s|%s", upay_id, user_tel)
    headers = {'Cookie': 'upay_user=%s;' % upay_id, 'Host': 'upay.10010.com',
               'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:62.0) Gecko/20100101 Firefox/62.0',
               'X-Requested-With': 'XMLHttpRequest',
               'Referer': 'http://upay.10010.com/npfwap/npfMobWap/bankcharge/index.html?version=wap&desmobile=6672070486447365',
               # 'CLIENT-IP': ip,
               # 'X-FORWARDED-FOR': ip,
               }
    proxys = await redis.smembers('un_proxy', encoding='utf-8')
    if not proxys:
        return {"code": -1, 'message': "无代理可用"}
    proxy = random.choice(list(proxys))
    logger.info("代理%s|%s", user_tel, proxy)
    if proxy:
        conn = proxy
    else:
        conn = None
    logger.info(conn)
    try:
        async with aiohttp.ClientSession(headers=headers) as session:
            prov_url = 'http://upay.10010.com/npfwap/npfMobWeb/getArea/init?callback=jQuery&commonBean.phoneNo=%s&_=%s' % (user_tel, get_ts())
            async with session.get(prov_url, proxy=conn) as rsp:
                body = await rsp.text()
                area = re.findall('(\d+)', body)
            if not area:
                return {"code": -1, "message": rsp.content.decode()}
            card_info = card.get(str(amount), {})
            if card_info:
                bussine_type = '06'
                userChooseMode = '0'
            else:
                bussine_type = '01'
                userChooseMode = ''
            data = {
                'browserVersion': '',
                'bussineTypeInput': '0',
                'cardBean.cardValue': card_info.get('cardValue', ''),
                'cardBean.cardValueCode': card_info.get('cardValCode', ''),
                'channelKey': '',
                'commonBean.activityType': '',
                'commonBean.areaCode': '',
                'commonBean.bussineType': bussine_type,
                'commonBean.channelCode': 'weixinH5',
                'commonBean.channelType': '307',
                'commonBean.cityCode': area[1],
                'commonBean.netAccount': '',
                'commonBean.offerate': card_info.get('offerRate', ''),
                'commonBean.offerateId': card_info.get('offerateId', ''),
                'commonBean.orgCode': '31',
                'commonBean.payAmount': amount,
                'commonBean.phoneNo': user_tel,
                'commonBean.provinceCode': area[0],
                'commonBean.reserved1': 'false',
                'commonBean.ticketNo': '',
                'commonBean.userChooseMode': userChooseMode,
                'invoiceBean.card_type': '',
                'invoiceBean.id_cardno': '',
                'invoiceBean.invoice_head': '',
                'invoiceBean.invoice_type': '',
                'invoiceBean.is_mailing': '0',
                'invoiceBean.need_invoice': '0',
                'numberType': '',
                'pointBean.payMethod': '',
                'pointBean.pointNumber': '',
                'ticketNew': ticket,
            }
            # print(data)
            url = 'http://upay.10010.com/npfwap/NpfMob/mobWapBankCharge/wapBankChargeCheck.action'
            async with session.post(url, data=data, headers=headers, proxy=conn) as rsp:
                res = await rsp.text()
                res = json.loads(res)
                logger.info(res)
                if res['out'] != 'success':
                    # if res['out'] == "您的操作太频繁，请稍后再试！":
                    #     await redis.srem("un_proxy", proxy)
                    result = {"code": -1, "message": res['out']}
                else:
                    result = {"code": 0}
                # # secstate = res['secstate']
    except Exception as e:
        logger.error(e, exc_info=True)
        result = {'code': -1, "message": "%s" % e}
    if "验证码校验异常" not in res.get("message", ""):
        upay_redis.lpush('tickets', json.dumps(upay_data))
    if "操作太频繁" in res.get("message", ""):
        redis.srem("un_proxy", conn)

    return result


async def get_weixin_h5(tel, amount, redis):
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36',
    }
    proxys = await redis.smembers('proxy', encoding='utf-8')
    proxy = random.choice(list(proxys))
    logger.info(proxy)
    amount = int(amount)
    if proxy:
        conn = proxy
    else:
        conn = None
    async with aiohttp.ClientSession(headers=headers) as session:
        url = 'https://webh5.qianxingniwo.com/api/MobileQuery/MobileQuery'
        data = {
            "pageNo": 7,
            "ph": tel
        }
        async with session.post(url, json=data, proxy=conn) as rsp:
            ph_data = await rsp.json()
            ph_data = json.loads(ph_data)
            # print(ph_data)
            logger.info(ph_data)
            if ph_data["code"] == 100:
                carrierNo = ph_data['data']['carrierNo']
                provinceNo = ph_data['data']['provinceNo']
                cityNo = ph_data['data']['cityNo']
                if carrierNo == '联通':
                    check_num = await get_unicom_wx(tel, '30', redis)
                    if check_num['code'] != 0:
                        return check_num
                elif carrierNo == '移动':
                    res = await aget_wxqrcode(tel, amount, redis)
                    if res["retCode"] != "000000":
                        logger.info("%s不可交费", tel)
                        return {"code": -1, 'message': res.get("retMsg")}
            else:
                return {'code': -1, "message": ph_data.get("msg")}

        url = 'https://webh5.qianxingniwo.com/api/MobileQuery/ProductQuery'
        data = {"ptype": 0, "bt": 1, "pageNo": 7, "rm": -1, "merge_type": 3, "ph": tel, "province": provinceNo,
                "carrier": carrierNo, "cityNo": cityNo}
        async with session.post(url, json=data, proxy=conn) as rsp:
            face_data = await rsp.json()
            face_data = json.loads(face_data)
            if face_data['code'] == 100:
                for prduct in face_data['data']:
                    if prduct['businessType'] == 2 and prduct['face'] == amount and prduct['rechargeMode'] == 0:
                        productID = prduct['productID']
                        price = prduct['payFee']
                        break
                else:
                    return {"code": -1, "message": '未找到金额'}
            else:
                return {"code": -1, "message": face_data['msg']}

        data = {
            'Acount': tel,
            'BusinessType': 2,
            'CardType': 1,
            'CouponCh': '',
            'CouponFace': '',
            'CouponId': '',
            'Face': amount,
            'FlowType': '',
            'Mobile': tel,
            'PayType': 2,
            'Price': price,
            'ProductId': productID,
            'ProductName': '充话费-%d元' % amount,
            'RechargeMode': 0,
            'pageNo': 7}
        # 10086 下单
        url = 'https://webh5.qianxingniwo.com/api/PayRequest/OrderPayRequest'
        async with session.post(url, json=data, proxy=conn) as rsp:
            data = await rsp.json()
            logger.info(data)
            # print(data)
            data = json.loads(data)
            if data['Code'] == 100:
                pay_data = json.loads(data['Data'])
                pay_url = pay_data['url']
                order = pay_data['order']
                appid = pay_data['appid']
                # print({'code': 0, 'url': pay_url, "orderid": order, "appid": appid})
                # return {'code': 0, 'url': pay_url, "orderid": order, "appid": appid}
            else:
                return {'code': -1, 'message': data['Msg']}

        headers['Host'] = 'wx.tenpay.com'
        headers['Referer'] = 'https://webh5.qianxingniwo.com/pay/hwpayment'
        async with session.get(pay_url, headers=headers, proxy=conn) as rsp:
            text = await rsp.text()
            # print(text)
            url = re.findall('"(weixin.*)"', text)
            logger.info(url)
            if carrierNo == "移动":
                tel_type = 'cmcc'
            elif carrierNo == '联通':
                tel_type = 'unicom'
            elif carrierNo == '电信':
                tel_type = 'ctcc'
            else:
                tel_type = ''

            return {'code': 0, 'url': url[0], "orderid": order, "appid": appid, "tel_type": tel_type, "prov": provinceNo}

async def cmcc_query(order_id, tel, redis):
    url = 'https://webh5.qianxingniwo.com/api/OrderQuery/QueryOrderByOrder'
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36',
    }
    proxys = await redis.smembers('proxy', encoding='utf-8')
    proxy = random.choice(list(proxys))
    logger.info(proxy)
    if proxy:
        conn = proxy
    else:
        conn = None

    data = {"order": order_id}
    async with aiohttp.ClientSession(headers=headers) as session:
        async with session.post(url, json=data, proxy=conn) as rsp:
            text = await rsp.json()
            order_info = json.loads(text)
            logger.info(order_info)
            if order_info['Code'] == 300:
                orderstate = '8'
            elif order_info['Code'] == 100:
                res_info = json.loads(order_info["Data"])
                if res_info['Status'] == '充值成功':
                    orderstate = '0'
                else:
                    orderstate = '9'

            message = order_info['Msg']

            return orderstate,  message


async def qx_query(order_id, appid, redis):
    url = 'https://webh5.qianxingniwo.com/api/OrderNotify/QueryOrderState'
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36',
    }
    proxys = await redis.smembers('proxy', encoding='utf-8')
    proxy = random.choice(list(proxys))
    logger.info(proxy)
    if proxy:
        conn = proxy
    else:
        conn = None

    # data = {"order": order_id}
    data = {"orderno": order_id, "appid": appid, "acctype": "2", "pay_type": 2}

    async with aiohttp.ClientSession(headers=headers) as session:
        async with session.post(url, json=data, proxy=conn) as rsp:
            text = await rsp.json()
            order_info = json.loads(text)
            print(order_info)
            if order_info['Data'] == 'NOTPAY':
                orderstate = '8'
            elif order_info['Data'] == "SUCCESS":
                orderstate = '0'
            message = order_info['Msg']

            return orderstate, message


if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    now = time.time()
    redis = loop.run_until_complete(
        aioredis.create_redis(address=('localhost', 6379), db=0, loop=loop)
    )
    # task = asyncio.ensure_future(get_weixin_h5("13418071372", "30", redis))
    task = asyncio.ensure_future(qx_query("QX201812242255021670", "wxe895c11cbeeadcfe", redis))
    loop.run_until_complete(task)
    print(time.time() - now)
    loop.close()
